const connection = require('../app/database');

class MomentService {
    async getMomentList(page = '0', size = '0', type_id) {
        let result;
        let count;
        let offset = page - 1;
        offset = offset * size;
        console.log('offset', offset);
        if (!type_id) {
            const statement = `SELECT id, title, img_url, introduce, create_time, update_time, type_id FROM moment Order By create_time Desc LIMIT ?,?;`;
            [result] = await connection.execute(statement, [offset, size]);

            const statement1 = `SELECT COUNT(*) as page FROM moment; `;
            count = await connection.execute(statement1);
            count = JSON.parse(JSON.stringify(count))[0][0].page;
        } else {
            const statement = `SELECT id, title, img_url, introduce, create_time, update_time, type_id FROM moment WHERE type_id=? Order By create_time Desc LIMIT ?,?;`;
            [result] = await connection.execute(statement, [type_id, offset, size]);
            const statement1 = `SELECT COUNT(*) as page FROM moment WHERE type_id =?; `;
            count = await connection.execute(statement1, [type_id]);
            count = JSON.parse(JSON.stringify(count))[0][0].page;
        }


        return {
            code: 0,
            message: '',
            data: {
                page: page * 1,
                size: result.length,
                total: count,
                data: result
            }
        };

    }
    async create(moment) {
        const { title, introduce = '', content, type_id, img_url } = moment;
        const statement = `INSERT INTO moment (title,introduce,content,type_id,img_url) VALUES (?,?,?,?,?);`;

        const result = await connection.execute(statement, [title, introduce, content, type_id, img_url])

        return result;
    }
    async getMomentById(momentId) {
        const statement = `SELECT * FROM moment WHERE id=?;`;

        const result = await connection.execute(statement, [momentId])

        return {
            code: 0,
            message: '',
            data: result[0][0]
        };
    }
    async edit(moment) {
        const { id, title, introduce, content, type_id, img_url } = moment;
        const statement = `UPDATE moment SET title = ?,introduce = ?,content = ?,type_id = ?,img_url = ? WHERE id = ?;`;

        const result = await connection.execute(statement, [title, introduce, content, type_id, img_url, id])

        return result;
    }
    async remove(momentId) {
        const statement = `DELETE FROM moment WHERE id = ?;`;

        const result = await connection.execute(statement, [momentId])

        return result
    }
}

module.exports = new MomentService();